package com.zhang.third.day02;

import org.apache.flink.api.common.functions.Partitioner;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @title: 自定义物理分区
 * @author: zhang
 * @date: 2022/4/2 17:20
 */
public class CustomPartition {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env
                .fromElements(1, 2, 3, 4, 5, 6, 7, 8, 9).setParallelism(1)
                .partitionCustom(
                        new Partitioner<Integer>() {
                            @Override
                            public int partition(Integer key, int numPartitions) {
                                return key % numPartitions;
                                // 1 % 2 = 1 => 2
                                // 2 % 2 = 0 => 1
                            }
                        },
                        // 为每一个数据指定key
                        // 每来一条数据就指定一个key
                        new KeySelector<Integer, Integer>() {
                            @Override
                            public Integer getKey(Integer value) throws Exception {
                                return value;
                            }
                        }
                )
                .print().setParallelism(2);
        /**
         * 1> 2
         * 1> 4
         * 1> 6
         * 1> 8
         * 2> 1
         * 2> 3
         * 2> 5
         * 2> 7
         * 2> 9
         */

        env.execute();
    }
}
